/* James McTaggart (jcm28) Informatics
Multimedia Communications Technology - 17th May 2007
In making this submission I declare that my work contains no examples
of misconduct, such as plagiarism, collusion, or fabrication of results.
*/

package server;

import java.net.DatagramPacket;
import java.net.InetAddress;

public final class ServerProtocol {

	public static DatagramPacket get201(int clientPort, InetAddress clientAddress, 
			int delay, int period, String radioAddress, int radioPort){
		byte[] outData = new byte[60];
		String header = "201CONNECTED";
		System.arraycopy(header.getBytes(), 0, outData, 0, header.length());
		//The body contains Delay (6 bytes) Period (6 bytes) Radio port (4 bytes)
		//and from then radio address surrounded by #(address)#
		String body = "" + padNumber(delay) + padNumber(period) + radioPort + "#" + radioAddress +"#";
		System.arraycopy(body.getBytes(), 0, outData, 13, body.length());
		return new DatagramPacket(outData,outData.length,clientAddress,clientPort);
	}
	
	public static DatagramPacket get202(InetAddress ip, int port){
		String header = "202STARTBLEEP";
		byte[] outData = new byte[60];
		System.arraycopy(header.getBytes(), 0, outData, 0, header.length());
		return new DatagramPacket(outData,outData.length,ip,port);
	}
	
	public static DatagramPacket get203(InetAddress ip, int port){
		String header = "203STOPBLEEP";
		byte[] outData = new byte[60];
		System.arraycopy(header.getBytes(), 0, outData, 0, header.length());
		return new DatagramPacket(outData,outData.length,ip,port);
	}
	
	public static DatagramPacket get401(String nextSample, int counter,InetAddress ipAddress, int port){
		String header = "401SAMP" + padNumber(counter);
		byte[] outData = new byte[60];
		System.arraycopy(header.getBytes(), 0, outData, 0, header.length());
		System.arraycopy(nextSample.getBytes(), 0, outData, header.length(), nextSample.length());
		return new DatagramPacket(outData,outData.length,ipAddress,port);
		
	}
	
	public static DatagramPacket get402(int retransmitNo,int port, InetAddress ip){
		byte[] outData = new byte[60];
		//Copy the header
		String header = "402RETR" + padNumber(retransmitNo);
		System.arraycopy(header.getBytes(), 0, outData, 0, header.length());
		//From byte 0 of the data section have the restransmitted string surrounded by #
		String retransmitSample = RadioTimerTask.decodeMessageIDForRetransmit(retransmitNo);
		System.arraycopy(retransmitSample.getBytes(), 0, outData, 19, retransmitSample.length());
		return new DatagramPacket(outData,outData.length,ip,port);
	}
	
	public static String padNumber(int number){
		String result = "";
		if(number==0)return "000000";
		//Get the length of the number
		int i = (int)Math.floor(Math.log10(number));
		for(int j = 0; j<(5-i); j++)result+="0";
		result += number;
		return result;
	}
}
